package com.sys.ai.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.sys.ai.domain.AiWorkflow;
import com.sys.ai.fo.AiWorkFlowExecuteFO;
import com.sys.ai.service.IAiWorkflowService;
import com.sys.common.annotation.Log;
import com.sys.common.core.controller.BaseController;
import com.sys.common.core.domain.AjaxResult;
import com.sys.common.core.page.TableDataInfo;
import com.sys.common.enums.BusinessType;
import com.sys.common.exception.ServiceException;
import com.sys.common.utils.StringUtils;
import com.sys.common.utils.poi.ExcelUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * AI流程Controller
 *
 * @author LGY
 * @date 2025-05-23
 */
@Slf4j
@Tag(name = "AI流程")
@RestController
@RequestMapping("/ai/aiWorkflow")
public class AiWorkflowController extends BaseController {
    @Autowired
    private IAiWorkflowService aiWorkflowService;

    /**
     * 查询AI流程列表
     */
    @PostMapping("/list")
    @Operation(summary = "查询AI流程分页列表")
    public TableDataInfo list(@RequestBody AiWorkflow aiWorkflow) {
        startPage(aiWorkflow);
        List<AiWorkflow> list = aiWorkflowService.selectAiWorkflowList(aiWorkflow);
        return getDataTable(list);
    }

    @Operation(summary = "查询所有已发布的AI流程列表")
    @GetMapping("/listAllRelease")
    public AjaxResult listAllRelease() {
        List<AiWorkflow> list = aiWorkflowService.listAllRelease();
        return success(list);
    }

    /**
     * 导出AI流程列表
     */
    @Log(title = "AI流程", businessType = BusinessType.EXPORT)
    @Operation(summary = "导出AI流程")
    @PostMapping("/export")
    public void export(HttpServletResponse response, AiWorkflow aiWorkflow) {
        List<AiWorkflow> list = aiWorkflowService.selectAiWorkflowList(aiWorkflow);
        ExcelUtil<AiWorkflow> util = new ExcelUtil<AiWorkflow>(AiWorkflow.class);
        util.exportExcel(response, list, "AI流程数据");
    }

    /**
     * 获取AI流程详细信息
     */
    @Operation(summary = "查询AI流程详情")
    @GetMapping(value = "/detail/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(aiWorkflowService.selectAiWorkflowById(id));
    }

    /**
     * 新增AI流程
     */
    @Log(title = "AI流程", businessType = BusinessType.INSERT)
    @Operation(summary = "新增AI流程")
    @PostMapping("/save")
    public AjaxResult add(@RequestBody AiWorkflow aiWorkflow) {
        aiWorkflowService.insertAiWorkflow(aiWorkflow);
        return success();
    }

    /**
     * 修改AI流程
     */
    @Log(title = "AI流程", businessType = BusinessType.UPDATE)
    @Operation(summary = "修改AI流程")
    @PutMapping("/update")
    public AjaxResult edit(@RequestBody AiWorkflow aiWorkflow) {
        aiWorkflowService.updateAiWorkflow(aiWorkflow);
        return success();
    }

    @Log(title = "AI流程", businessType = BusinessType.UPDATE)
    @Operation(summary = "发布AI流程")
    @PutMapping("/release/{id}")
    public AjaxResult release(@PathVariable("id") String id) {
        AiWorkflow aiWorkflow = aiWorkflowService.getById(id);
        if (StringUtils.isBlank(aiWorkflow.getGraph())) {
            throw new ServiceException("未设计流程，不能进行发布");
        }
        JSONObject jsonObject = JSONObject.parseObject(aiWorkflow.getGraph());
        JSONArray jsonArray = jsonObject.getJSONArray("nodes");

        List<String> nodeTypeList = new ArrayList<>();
        jsonArray.forEach(node -> {
            JSONObject nodeObj = (JSONObject) node;
            String nodeType = nodeObj.getString("type");
            nodeTypeList.add(nodeType);
        });
        if (!nodeTypeList.contains("startNode")) {
            throw new ServiceException("流程未添加开始节点");
        }
         if (!nodeTypeList.contains("endNode")) {
            throw new ServiceException("流程未添加结束节点");
        }
        aiWorkflow.setStatus(1);
        aiWorkflowService.updateAiWorkflow(aiWorkflow);
        return success();
    }

    @Operation(summary = "AI流程设计保存")
    @Log(title = "AI流程", businessType = BusinessType.UPDATE)
    @PutMapping("/design")
    public AjaxResult design(@RequestBody AiWorkflow aiWorkflow) {
        AiWorkflow data = aiWorkflowService.getById(aiWorkflow.getId());
        JSONObject jsonObject = JSONObject.parseObject(data.getGraph());
        data.setGraph(JSON.toJSONString(jsonObject));
        aiWorkflowService.updateAiWorkflow(aiWorkflow);
        return success();
    }

    @Operation(summary = "AI流程执行")
    @PostMapping("/execute")
    public AjaxResult execute(@RequestBody AiWorkFlowExecuteFO aiWorkFlowExecuteFO) {
        log.info("执行AI流程入参：{}", JSON.toJSONString(aiWorkFlowExecuteFO));
        Map<String, Object> res = aiWorkflowService.executeWorkFlow(aiWorkFlowExecuteFO.getGraph(), aiWorkFlowExecuteFO.getParams(),
                aiWorkFlowExecuteFO.getCustomType());
        return success(res);
    }

    /**
     * 删除AI流程
     */
    @Operation(summary = "删除AI流程")
    @Log(title = "AI流程", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        aiWorkflowService.deleteAiWorkflowByIds(ids);
        return success();
    }
}
